package com.qk.state.config;

import com.qk.enums.BusinessEvent;
import com.qk.enums.BusinessState;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/**
 * @author 28188
 */
@Configuration
@EnableStateMachine(name = "BusinessStateMachine")
public class BusinessStateMachineConfig extends StateMachineConfigurerAdapter<BusinessState, BusinessEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<BusinessState, BusinessEvent> states) throws Exception {
        states
                .withStates()
                .initial(BusinessState.UNASSIGNED)
                .states(EnumSet.allOf(BusinessState.class))
                .end(BusinessState.CONVERTED_TO_CUSTOMER)
                // 回收也是终态
                .end(BusinessState.RECYCLED);
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<BusinessState, BusinessEvent> transitions) throws Exception {
        transitions
                // 待分配 → 待跟进
                .withExternal()
                .source(BusinessState.UNASSIGNED)
                .target(BusinessState.PENDING_FOLLOWUP)
                .event(BusinessEvent.ASSIGN)
                .and()

                // 待跟进 → 跟进中
                .withExternal()
                .source(BusinessState.PENDING_FOLLOWUP)
                .target(BusinessState.FOLLOWING_UP)
                .event(BusinessEvent.START_FOLLOWUP)
                .and()

                // 跟进中 → 回收
                .withExternal()
                .source(BusinessState.FOLLOWING_UP)
                .target(BusinessState.RECYCLED)
                .event(BusinessEvent.RECYCLE)
                .and()

                // 跟进中 → 转客户
                .withExternal()
                .source(BusinessState.FOLLOWING_UP)
                .target(BusinessState.CONVERTED_TO_CUSTOMER)
                .event(BusinessEvent.CONVERT_TO_CUSTOMER)
                .and()

                // 跟进中 → 跟进中（自环，继续跟进）
                .withExternal()
                .source(BusinessState.FOLLOWING_UP)
                .target(BusinessState.FOLLOWING_UP)
                .event(BusinessEvent.START_FOLLOWUP)
                .and()

                // 回收 → 待分配（重新分配）
                .withExternal()
                .source(BusinessState.RECYCLED)
                .target(BusinessState.UNASSIGNED)
                .event(BusinessEvent.REASSIGN);
    }
}
